5月 7 2015 Online Judge►LeetCode [LeetCode] 124 - Binary Tree Maximum Path Sum 題意求出一條路徑的和最大,起點和終點可以是任意點。 解法對經過當前的node來說,最大路徑有下面幾種可能: node 左邊+node node+右邊 左邊+node+右邊 心得乍看之下覺得似乎很簡單,但沒想到負數會這麼麻煩,也沒想到把最大值拉到外層就能解決許多問題 .. 程式12345678910111213141516171819202122232425262728293031/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxnum = -999999 ; int FindMax(TreeNode* node){ if ( node == NULL ) return 0 ; int left = FindMax(node->left) ; int right = FindMax(node->right) ; int nowmax = node->val ; if ( left > 0 ) nowmax += left ; if ( right > 0 ) nowmax += right ; if ( nowmax > maxnum ) maxnum = nowmax ; return max(node->val,max(node->val+left,node->val+right)) ; } int maxPathSum(TreeNode* root) { FindMax(root) ; return maxnum ; }}; Newer [LeetCode] 55 - Jump Game Older [LeetCode] 19 - Remove Nth Node From End of List